// internal/dao/search_dao.go
package dao

import (
	"time"

	"github.com/jfastfiler/internal/model"
)

type SearchDAO struct {
	db *gorm.DB
}

func NewSearchDAO(database *Database) *SearchDAO {
	return &SearchDAO{db: database.db}
}

func (dao *SearchDAO) SaveSearchHistory(history *model.SearchHistory) error {
	return dao.db.Create(history).Error
}

func (dao *SearchDAO) GetSearchHistory(userID int, limit int) ([]model.SearchHistory, error) {
	var history []model.SearchHistory
	err := dao.db.Where("user_id = ?", userID).Order("timestamp DESC").Limit(limit).Find(&history).Error
	return history, err
}

func (dao *SearchDAO) GetPopularSearches(limit int, days int) ([]PopularSearch, error) {
	var popular []PopularSearch
	
	startTime := time.Now().AddDate(0, 0, -days)
	
	err := dao.db.Model(&model.SearchHistory{}).
		Select("keyword, COUNT(*) as search_count").
		Where("timestamp > ?", startTime).
		Group("keyword").
		Order("search_count DESC").
		Limit(limit).
		Scan(&popular).Error
	
	return popular, err
}

func (dao *SearchDAO) ClearOldSearchHistory(days int) error {
	cutoffTime := time.Now().AddDate(0, 0, -days)
	return dao.db.Where("timestamp < ?", cutoffTime).Delete(&model.SearchHistory{}).Error
}

type PopularSearch struct {
	Keyword     string `json:"keyword"`
	SearchCount int    `json:"search_count"`
}